<template>
  <div class="min-h-screen flex items-center justify-center relative overflow-hidden py-12 px-4 sm:px-6 lg:px-8">
    <!-- 背景装饰 -->
    <div class="absolute inset-0 bg-gradient-to-br from-primary-50 via-purple-50 to-pink-50 dark:from-gray-900 dark:via-purple-900/20 dark:to-pink-900/20">
      <div class="absolute top-0 -left-4 w-72 h-72 bg-purple-300 dark:bg-purple-600 rounded-full mix-blend-multiply dark:mix-blend-overlay filter blur-xl opacity-30 animate-blob"></div>
      <div class="absolute top-0 -right-4 w-72 h-72 bg-pink-300 dark:bg-pink-600 rounded-full mix-blend-multiply dark:mix-blend-overlay filter blur-xl opacity-30 animate-blob animation-delay-2000"></div>
      <div class="absolute -bottom-8 left-20 w-72 h-72 bg-primary-300 dark:bg-primary-600 rounded-full mix-blend-multiply dark:mix-blend-overlay filter blur-xl opacity-30 animate-blob animation-delay-4000"></div>
    </div>

    <!-- 主内容 -->
    <div class="max-w-md w-full relative z-10">
      <!-- Logo 和标题 -->
      <div class="text-center mb-8">
        <div class="flex justify-center mb-4">
          <div class="p-3 rounded-2xl bg-gradient-to-br from-primary-600 to-purple-600 shadow-lg">
            <Icon name="heroicons:code-bracket" class="w-8 h-8 text-white" />
          </div>
        </div>
        <h2 class="text-3xl font-bold gradient-text mb-2">
          注册开发者导航账号
        </h2>
        <p class="text-gray-600 dark:text-gray-400">
          开启您的开发工具探索之旅
        </p>
      </div>

      <!-- 注册卡片 -->
      <div class="card p-8 shadow-2xl backdrop-blur-sm bg-white/80 dark:bg-gray-800/80">
        <form @submit.prevent="handleRegister" class="space-y-5">
          <!-- 昵称输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              昵称
            </label>
            <div class="relative">
              <Icon name="heroicons:user" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="form.nickname"
                type="text"
                required
                class="input pl-10"
                placeholder="请输入昵称"
              />
            </div>
          </div>

          <!-- 邮箱输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              邮箱地址
            </label>
            <div class="relative">
              <Icon name="heroicons:envelope" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="form.email"
                type="email"
                required
                class="input pl-10"
                placeholder="请输入邮箱"
              />
            </div>
          </div>

          <!-- 密码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              密码
            </label>
            <div class="relative">
              <Icon name="heroicons:lock-closed" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                required
                minlength="6"
                class="input pl-10 pr-10"
                placeholder="至少6位密码"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
              >
                <Icon :name="showPassword ? 'heroicons:eye-slash' : 'heroicons:eye'" class="w-5 h-5" />
              </button>
            </div>
            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
              密码长度至少6位，建议包含字母和数字
            </p>
          </div>

          <!-- 确认密码 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              确认密码
            </label>
            <div class="relative">
              <Icon name="heroicons:lock-closed" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="form.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                required
                class="input pl-10 pr-10"
                placeholder="请再次输入密码"
              />
              <button
                type="button"
                @click="showConfirmPassword = !showConfirmPassword"
                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
              >
                <Icon :name="showConfirmPassword ? 'heroicons:eye-slash' : 'heroicons:eye'" class="w-5 h-5" />
              </button>
            </div>
          </div>

          <!-- 图形验证码 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              验证码
            </label>
            <div class="flex space-x-2">
              <input
                v-model="form.captcha"
                type="text"
                required
                class="input flex-1"
                placeholder="请输入验证码"
                maxlength="4"
              />
              <div
                v-html="captchaSvg"
                @click="refreshCaptcha"
                class="cursor-pointer bg-gray-100 dark:bg-gray-700 rounded-lg p-2 hover:opacity-80 transition-opacity"
                style="width: 120px; height: 40px;"
              />
            </div>
          </div>

          <!-- 用户协议 -->
          <div class="flex items-start">
            <input
              id="agree"
              v-model="form.agree"
              type="checkbox"
              required
              class="mt-1 rounded border-gray-300 text-primary-600 focus:ring-primary-500 mr-2"
            />
            <label for="agree" class="text-sm text-gray-600 dark:text-gray-400">
              我已阅读并同意
              <NuxtLink to="/terms" class="text-primary-600 hover:text-primary-700 dark:text-primary-400">
                《服务条款》
              </NuxtLink>
              和
              <NuxtLink to="/privacy" class="text-primary-600 hover:text-primary-700 dark:text-primary-400">
                《隐私政策》
              </NuxtLink>
            </label>
          </div>

          <!-- 注册按钮 -->
          <button
            type="submit"
            :disabled="isLoading"
            class="btn btn-primary w-full"
          >
            <Icon v-if="isLoading" name="svg-spinners:180-ring" class="w-5 h-5" />
            <span>{{ isLoading ? '注册中...' : '立即注册' }}</span>
          </button>
        </form>
      </div>

      <!-- 登录提示 -->
      <p class="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
        已有账号？
        <NuxtLink to="/login" class="text-primary-600 hover:text-primary-700 dark:text-primary-400 font-medium">
          立即登录
        </NuxtLink>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
// 已登录用户不能访问注册页
definePageMeta({
  middleware: ['guest'],
})

const authStore = useAuthStore()
const route = useRoute()
const { $api } = useNuxtApp()
const toast = useToast()

// 表单
const form = ref({
  nickname: '',
  email: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  agree: false,
})

const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 图形验证码
const captchaSvg = ref('')
const captchaId = ref('')

// 加载状态
const isLoading = ref(false)

/**
 * 获取图形验证码
 */
const refreshCaptcha = async () => {
  try {
    const response: any = await $api('/auth/captcha')
    captchaSvg.value = response.captchaSvg
    captchaId.value = response.captchaId
  } catch (error) {
    console.error('获取验证码失败', error)
  }
}

/**
 * 处理注册
 */
const handleRegister = async () => {
  // 验证密码
  if (form.value.password !== form.value.confirmPassword) {
    return toast.warning('两次输入的密码不一致')
  }

  if (form.value.password.length < 6) {
    return toast.warning('密码长度至少6位')
  }

  if (!form.value.agree) {
    return toast.warning('请同意服务条款和隐私政策')
  }

  try {
    isLoading.value = true

    // 验证图形验证码
    const verifyResult: any = await $api('/auth/captcha/verify', {
      method: 'POST',
      body: {
        captchaId: captchaId.value,
        code: form.value.captcha,
      },
    })

    if (!verifyResult.valid) {
      toast.error(verifyResult.message || '验证码错误')
      refreshCaptcha()
      form.value.captcha = ''
      return
    }

    // 注册
    const response: any = await $api('/auth/register', {
      method: 'POST',
      body: {
        nickname: form.value.nickname,
        email: form.value.email,
        password: form.value.password,
      },
    })

    // 保存登录状态
    authStore.setToken(response.token)
    authStore.setUser(response.user)

    // 显示成功提示
    toast.success('注册成功！欢迎加入')

    // 跳转
    const redirect = route.query.redirect as string || '/'
    setTimeout(() => navigateTo(redirect), 500)
  } catch (error: any) {
    toast.error(error.data?.message || '注册失败，请稍后重试')
    refreshCaptcha()
    form.value.captcha = ''
  } finally {
    isLoading.value = false
  }
}

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha()
})

// SEO
useHead({
  title: '注册 - DevToolsHub',
  meta: [
    { name: 'description', content: '注册 DevToolsHub 账号，开始探索优质开发工具。' },
  ],
})
</script>

<style scoped>
@keyframes blob {
  0%, 100% {
    transform: translate(0, 0) scale(1);
  }
  33% {
    transform: translate(30px, -50px) scale(1.1);
  }
  66% {
    transform: translate(-20px, 20px) scale(0.9);
  }
}

.animate-blob {
  animation: blob 7s infinite;
}

.animation-delay-2000 {
  animation-delay: 2s;
}

.animation-delay-4000 {
  animation-delay: 4s;
}
</style>

